package cc.messcat.web.fupin;

import cc.messcat.common.constant.CommonConstant;
import cc.messcat.common.constant.CommonRedisConstant;
import cc.messcat.common.model.Pager;
import cc.messcat.common.model.ResponseBean;
import cc.messcat.entity.app.StartupIMG;
import cc.messcat.entity.fupin.Family;
import cc.messcat.entity.fupin.PoorFamily;
import cc.messcat.entity.fupin.VisitRecd;
import cc.messcat.entity.helpPerson.HelpPerson;
import cc.messcat.entity.system.ApplicationProperties;
import cc.messcat.entity.system.McUser;
import cc.messcat.entity.system.Permission;
import cc.messcat.entity.system.Role;
import cc.messcat.log.OperationLog;
import cc.messcat.service.app.StartupIMGService;
import cc.messcat.service.fupin.PoorFamilyService;
import cc.messcat.service.fupin.VisitRecdService;
import cc.messcat.util.Collections;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * app支持 
 */
@Controller
@RequestMapping("app")
public class ApplicationSupportController {

	Logger log = LoggerFactory.getLogger(ApplicationSupportController.class);
	
	private static final String EXTENSION = ".apk";
	
	/**
	 * app启动页面路径
	 */
	private static final String STARTUP_IMG_PATH = "/img/app";
	
	@Autowired
	private StartupIMGService startupIMGService;
	@Autowired
	private PoorFamilyService poorFamilyService;
	@Autowired
	private VisitRecdService visitRecdService;
	/**
	 * 检查更新
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("checkUpdate")
	@ResponseBody
	public Object checkUpdate(@RequestParam(name="version",required = true)String version,
		HttpServletResponse response,HttpSession session) throws IOException {
		String basePath = session.getServletContext().getRealPath("/app");
		File file = new File(basePath );
		Map<String,String> result = null;
		if(!file.exists()) {
			file.mkdirs();
		}
		
		for (File e : file.listFiles()) {
			if(e.isFile() && e.getName().contains(EXTENSION) && !FilenameUtils.getBaseName(e.getName()).equalsIgnoreCase(version) ) {
				log.info("找到更新安装包："+ session.getServletContext().getContextPath()+"/app/update/" + e.getName());
				result = new HashMap<>();
				result.put("version", FilenameUtils.getBaseName(e.getName()));
				result.put("length", String.valueOf(e.length()));
				result.put("url", session.getServletContext().getContextPath()+"/app/update/"+FilenameUtils.getBaseName(e.getName()));
				
				break;
			}
		}
		
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_SUCCESS,result);
	}
	
	
	/**
	 * 获取更新
	 * @throws IOException
	 */
	@OperationLog(desc="app更新",module="app")
	@RequestMapping("update/{version}")
	@ResponseBody
	public void update(@PathVariable(value="version") String version,HttpServletResponse response,HttpSession session) throws IOException {

		File update = new File(session.getServletContext().getRealPath("/app") + "/" + version + EXTENSION);
		if(update.exists()) {
			response.setHeader("Content-Disposition",	"attachment;filename="+version+ EXTENSION);
			response.setContentType("application/vnd.android.package-archive;charset=UTF-8");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			
			FileUtils.copyFile(update, response.getOutputStream());
		}
	}

	/**
	 * app启动页面上传
	 */
	@OperationLog(desc="app启动页面上传",module="app")
	@RequestMapping("addStartupIMG")
	@ResponseBody
    public Object addStartupIMG(
            MultipartFile file_1, Long id_1,
            MultipartFile file_2, Long id_2,
            MultipartFile file_3, Long id_3,
            HttpSession session) throws IOException {

        addStartupIMG(file_1, "1", id_1, session);
        addStartupIMG(file_2, "2", id_2, session);
        addStartupIMG(file_3, "3", id_3, session);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_SUCCESS);
    }
	/**
	 * app启动页面上传
	 */
	private void addStartupIMG(MultipartFile file,String ordinal,Long id,HttpSession session) throws IOException {
		//处理文件上传
		StringBuilder url = new StringBuilder("");
		String realPath = session.getServletContext().getRealPath(STARTUP_IMG_PATH);
		Random random = new Random();

		if (file == null || file.isEmpty()) {
			log.warn("文件未上传");
			return ;
		} else {
			String fileName = file.getOriginalFilename();
			fileName = "/a"+ordinal+"_"+ System.currentTimeMillis() + "_" + (random.nextInt(9000) + 1000)+"." + FilenameUtils.getExtension(fileName);
			url.append(STARTUP_IMG_PATH + fileName);
			FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, fileName));
		}
        if(id != null) {
            StartupIMG startupIMG = startupIMGService.retrieveObject(id);
            cleanStartupIMG( session.getServletContext().getRealPath("/"+startupIMG.getUrl()));
            startupIMG.setOrder(ordinal);
            startupIMG.setUrl(url.toString().replaceAll("^\\/", ""));
            return ;
        }
        StartupIMG startupIMG = new StartupIMG(new Date(),ordinal,url.toString().replaceAll("^\\/", ""));
		startupIMGService.addObject(startupIMG);
	}
	/**
	 * app启动页面相关记录清除
	 */
	private void cleanStartupIMG(String path)   {
       FileUtils.deleteQuietly(new File(path));
    }

	/**
	 * app启动页面获取
	 */
	@RequestMapping("listStartupIMG")
	@ResponseBody
	public Object listStartupIMG()   {

		List<StartupIMG> list = startupIMGService.listStartupIMG();
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_SUCCESS,list);
	}

	/**
	 * app启动页面url获取
	 */
	@RequestMapping("listStartupIMGURL")
	@ResponseBody
	public Object listStartupIMGURL()   {

		List<StartupIMG> list = startupIMGService.listStartupIMG();
		List<String> urls = new ArrayList<>();
		for(StartupIMG e : list) {
			urls.add(e.getUrl());
		}
		Map<Object, Object> result = Collections.generateHashMap("urls", urls);

		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_SUCCESS,result);
	}
	/**
	 * 用于手机端浏览器查询贫困户信息（不登录）
	 * @param id
	 * @param session
	 * @return
	 */
	@RequestMapping("/getPoorFamily")
	@ResponseBody
	public Object poorFamilyOnChrome(@RequestParam(value="number",required=true)String number,Integer pageNo, Integer pageSize, HttpSession session) {
		//根据户编号和年度查询贫困户
        //PoorFamily poorFamily = this.poorFamilyService.get(id);
		//根据户编号和当前年份查询贫困户
		//获取业务年度
		String annual = ApplicationProperties.getAnnual();
		PoorFamily poorFamily = this.poorFamilyService.getPoorFamilyByNumberAndAnnual(number,annual);
		
        List<HelpPerson> helpPerson = new ArrayList<>();
        List<Family> family = new ArrayList<>();
        Family f = new Family();
        if (poorFamily != null) {
            Iterator<HelpPerson> it = poorFamily.getHelpPersons().iterator();
            while (it.hasNext()) {
                HelpPerson next = it.next();
                if ("1".equalsIgnoreCase(next.getStatus())) helpPerson.add(next);
            }
            Iterator<Family> it2 = poorFamily.getFamily().iterator();
            while (it2.hasNext()) {
                Family next = it2.next();
                if("户主".equals(next.getRelation())){
                	f = next;
                }
                if ("0".equalsIgnoreCase(next.getIsDel())) family.add(next);
            }
        }else{
        	 return new ResponseBean(CommonConstant.FAIL_CODE_400, CommonConstant.MSG_FIND_FAIL, "该贫困户当前年份暂无数据");
        }

        PoorFamily viewPoorFamily = new PoorFamily();
        BeanUtils.copyProperties(poorFamily, viewPoorFamily);
        viewPoorFamily.setFamily(family);
        viewPoorFamily.setHelpPersons(helpPerson);

        Map map = new HashMap<>();
        map.put("poorFamily", viewPoorFamily);
        map.put("hname", f.getName());
        //帮扶日志（走访记录）
        VisitRecd visitRecd = new VisitRecd();
        visitRecd.setPoorFamily(poorFamily);
        if(pageNo == null){
        	pageNo = 1;
        }
        if(pageSize == null){
        	pageSize = 10;
        }
		Pager<VisitRecd> pager = visitRecdService.retrieveVisitRecdPager(pageNo, pageSize, visitRecd, null, null);
		List<VisitRecd> resultList = pager.getResultList();
		for (VisitRecd vr : resultList) {
			vr.setPoorFamily(null);
//			McUser addtor = vr.getAddtor();
//			addtor.setRoles(null);
			vr.setAddtor(null);
		}
		
        map.put("visitRecds", pager);
		
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, map);
	}
}
